# -*- coding: utf-8 -*-

from odoo import fields, models, api, _


class ProductProduct(models.Model):
    _inherit = "product.product"

    # 计算库位/ 筛选分组用
    storage_location_id = fields.Many2one('stock.location', compute='_compute_storage_location', store=True)
    s_contain_incoming_qty = fields.Float(string='Incoming(including requisition)',
                                          compute='_compute_s_contain_incoming_qty')

    @api.depends('categ_id')
    def _compute_s_contain_incoming_qty(self):
        for record in self:
            # 需要在原有的在途数上加上未下单的采购数
            # 采购订单未生成picking单,包含请购单
            pr_domain = [
                ('product_id', '=', record.product_tmpl_id.id),
                ('requisition_id.purchase_requisition_type', '=', 'material'),
                ('requisition_id.state', 'in', ['approved', 'section_purchasing', 'purchasing', 'done']),
                ('state', 'not in', ['closed', 'done'])
            ]
            close_pr_domain = [
                ('product_id', '=', record.product_tmpl_id.id),
                ('requisition_id.purchase_requisition_type', '=', 'material'),
                ('requisition_id.state', '=', 'closed'),
                ('state', '=', 'closed')
            ]
            close_pr_line_list = self.env['purchase.requisition.line']._read_group(close_pr_domain, ['id'], ['product_qty:sum'])
            close_pr_line_dict = {pr.id: val for pr, val in close_pr_line_list}
            pr_line_list = self.env['purchase.requisition.line']._read_group(pr_domain, ['id'], ['product_qty:sum'])
            pr_line_dict = {pr.id: val for pr, val in pr_line_list}
            # 下单数量
            pr_product_qty = round(sum(pr_line_dict.values(), 0), 4)
            # 请购生成的采购单数量, 需要排除已生成picking单的数量
            # 进一步获取采购单入库订单
            pl_domain = [
                ('pr_middle_ids.pr_line_id', 'in', list(pr_line_dict.keys())),
                ('state', '!=', 'cancel'),
                ('product_id', '=', record.id),
                ('s_close', '=', False)
            ]
            pl_line_list = self.env['purchase.order.line']._read_group(pl_domain, ['product_id', 'id'], ['qty_received:sum', 'product_qty:sum'])
            pl_line_dict = {}
            for pt, pl, val0, val1 in pl_line_list:
                if pt in pl_line_dict:
                    pl_line_dict[pt] += val1 if val0 > val1 else val0
                else:
                    pl_line_dict[pt] = val1 if val0 > val1 else val0
            close_pl_domain = [
                ('pr_middle_ids.pr_line_id', 'in', list(close_pr_line_dict.keys())),
                # ('pr_line_id.state', '=', 'closed'),
                ('state', '!=', 'cancel'),
                ('product_id', '=', record.id),
                ('s_close', '=', False)
            ]
            close_pl_line_list = self.env['purchase.order.line']._read_group(close_pl_domain, ['product_id', 'id'], ['qty_received:sum', 'product_qty:sum'])
            pre_close_pl_line_dict = {}
            don_close_pl_line_dict = {}
            for pt, pl, val0, val1 in close_pl_line_list:
                if pt in pre_close_pl_line_dict:
                    pre_close_pl_line_dict[pt] += val1
                    don_close_pl_line_dict[pt] += val0
                else:
                    pre_close_pl_line_dict[pt] = val1
                    don_close_pl_line_dict[pt] = val0
            # 接收数量  接收数量会进入库存量
            qty_received = round(pl_line_dict.get(record, 0), 4)
            # 加入单独创建采购单统计数量
            rpl_domain = [
                ('pr_middle_ids', '=', False),
                ('state', '!=', 'cancel'),
                ('product_id', '=', record.id),
                ('s_close', '=', False)
            ]
            rpl_line_list = self.env['purchase.order.line']._read_group(rpl_domain, ['product_id'],
                                                                        ['product_qty:sum', 'qty_received:sum'])
            rpl_list_dict = {p: q for _, p, q in rpl_line_list}
            # 未接收数量
            per_product_qty = round(sum(rpl_list_dict.keys(), 0), 4)
            per_close_product_qty = round(sum(pre_close_pl_line_dict.values(), 0), 4)
            pr_product_qty += per_product_qty
            pr_product_qty += per_close_product_qty
            don_received = round(sum(rpl_list_dict.values(), 0), 4)
            don_close_received_qty = round(sum(don_close_pl_line_dict.values(), 0), 4)
            qty_received += don_received
            qty_received += don_close_received_qty
            sum_qty = pr_product_qty - qty_received
            if sum_qty < 0:
                sum_qty = 0
            record.s_contain_incoming_qty = record.uom_po_id._compute_quantity(sum_qty, record.uom_id)  # 在途数

    # 自动计算产品的库位【首个分类上架规则的位置】
    @api.depends('categ_id')
    def _compute_storage_location(self):
        for re in self:
            # 查询首个分类上架规则位置
            pro_stock_location_rule_id = re.env['stock.putaway.rule'].sudo().search(
                [('category_id', '=', re.categ_id.id)], limit=1)
            if pro_stock_location_rule_id:
                re.storage_location_id = pro_stock_location_rule_id.location_out_id.id
            else:
                pro_stock_location_rule_par_id = re.env['stock.putaway.rule'].sudo().search(
                    [('category_id', '=', re.categ_id.parent_id.id)], limit=1)
                if pro_stock_location_rule_par_id:
                    re.storage_location_id = pro_stock_location_rule_par_id.location_out_id.id
                else:
                    re.storage_location_id = False

    @api.depends('name', 'default_code')
    def _compute_display_name(self):
        for rec in self:
            rec.display_name = rec.name

    def get_top_category(self, category):
        current = category
        while current and current.parent_id is not None:
            parent = current.parent_id
            if not parent:
                break
            current = parent
        return current
